var express = require('express');
var router = express.Router();

const meter = require("meterify").meterify;
const Web3 = require("web3");
const meterify = meter(new Web3(), "http://mainnet.meter.io:8669");


/**
 * 通过私钥获取地址
 */
router.post('/address', function (req, res) {
    // 获取传参
    const privateKey = req.body.privateKey;
    const account = meterify.eth.accounts.privateKeyToAccount(privateKey);
    res.set('Content-Type', 'application/json');
    res.send('{\"result\":\"' + account.address + '\"}');
});

/**
 * 签名
 */
router.post('/sign', function (req, res) {
    const params = req.body;
    const account = meterify.eth.accounts.privateKeyToAccount(params.privateKey);
    sign(params, account).then((signature) => {
        res.set('Content-Type', 'application/json');
        res.status(200).send(signature);
    }).catch(function (error) {
        console.log("Error: " + error);
        res.set('Content-Type', 'application/json');
        res.status(400).send('{"result":"' + error.message + '"}')
    });
});

router.get('/validateAddress/:address', function (req, res) {
    const params = req.params;
    res.set('Content-Type', 'application/json');
    const result = meterify.utils.isAddress(params.address);
    res.set('Content-Type', 'application/json');
    res.status(200).send('{"result":"' + result + '"}')
});

/**
 * 签名
 *
 * @param params
 * @param account
 * @returns {Promise<SignedTransaction>}
 */
async function sign(params, account) {
    return await meterify.eth.accounts.signTransaction({
        from: params.from,
        to: params.to,
        value: params.value,
        data: params.data
    }, account.privateKey);
}


module.exports = router;
